/**
 * 
 */
package com.zito.manager;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.downlove.common.DateUtils;
import com.downlove.common.RequestContext;
import com.downlove.database.QueryHelper;
import com.zito.ErrMsgException;
import com.zito.bean.Album;
import com.zito.bean.Albumphoto;
import com.zito.common.Paginator;

/**
 * @author YunHai-Home
 * 
 */
public class AlbumManager {

	private final Logger logger = LoggerFactory
			.getLogger(AlbumManager.class);

	private Paginator paginator;
	private Album album = new Album();

	/**
	 * 分页
	 * 
	 * @return
	 */
	public String getPaginator() {
		return this.paginator.getCssPageBlock();
	}

	public Paginator getPaginatorBean() {
		return this.paginator;
	}


	@SuppressWarnings("unchecked")
	public List<Album> albumList(int pagesize) {
		RequestContext rc = RequestContext.get();
		album = new Album();
		String filter = " 1 = 1 ";
		int total = album.TotalCount(filter);
		this.paginator = new Paginator(rc, total, pagesize);
		int totalpages = this.paginator.getTotalPages();
		int curpage = this.paginator.getCurrentPage();
		if (totalpages == 0) {
			curpage = 1;
			totalpages = 1;
		}
		List<Long> tmpList = album.idListFilter(filter, curpage, pagesize);
		return album.LoadList(tmpList);
	}
	
	@SuppressWarnings("unchecked")
	public List<Albumphoto> getalbumPhotoList(Long albumid) {
		Albumphoto obj = new Albumphoto();
		String sql = "SELECT * FROM albumphoto WHERE albumid=?";
		List<Long> List = QueryHelper.queryList(sql, albumid);
		return obj.LoadList(List);
	}
	
	/**
	 * 查询上一篇
	 * @param columnid
	 * @param articleid
	 * @param postdate
	 * @return
	 * @throws Exception
	 */
	public Album getLastAlbum(Long albumid,String postdate) throws Exception{
		String sql ="SELECT * FROM album WHERE posttime>=? AND ID != ? ORDER BY posttime Limit 1";
		Album obj = new Album();
		obj = QueryHelper.read(Album.class, sql, postdate,albumid);
		return obj;
	}
	

	/**
	 * 查询下一篇 
	 * @param columnid
	 * @param articleid
	 * @param postdate
	 * @return
	 * @throws Exception
	 */
	public Album getNextAlbum(Long albumid,String postdate) throws Exception{
		String sql ="SELECT * FROM album WHERE posttime<=? AND ID != ? ORDER BY posttime DESC Limit 1";
		Album obj = new Album();
		obj = QueryHelper.read(Album.class, sql, postdate,albumid);
		return obj;
	}
	
	/**
	 * 更新点击次数
	 * @return
	 */
	public boolean UpdateView(Long albumid) throws Exception{
		boolean re = false;
		String sql ="UPDATE album SET clicknum = clicknum+1 WHERE ID = ?";
		re = QueryHelper.update(sql, albumid)>0;
		return re;
	}
	
	public boolean operatingPost() throws ErrMsgException, IOException {
		RequestContext rc = RequestContext.get();
		long tempid = rc.param("id", -1);
		return tempid == -1 ? insertAlbum(rc) : editAlbum(rc);
	}

	public boolean insertAlbum(RequestContext rc)
			throws ErrMsgException, IOException {
		album = new Album();
		album = rc.form(Album.class);
		String error = album.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		album.setClicknum(0);
		album.setPosttime(DateUtils.getDateTime());
		return album.Save(RequestContext.get().session().getId()) != -1L;
	}

	public boolean editAlbum(RequestContext rc) throws ErrMsgException,
			IOException {
		album = new Album();
		album = rc.form(Album.class);
		if (album.getId() == -1)
			return false;
		String error = album.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		return album.Update(RequestContext.get().session().getId()) != -1L;
	}

	public Album getAlbum() {
		RequestContext rc = RequestContext.get();
		long id = rc.param("id", -1);
		if (id == -1)
			return null;
		return album.Get(id);

	}

	public boolean deleteAlbum() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		AlbumphotoManager obj = new AlbumphotoManager();
		album = new Album();
		album = rc.form(Album.class);
		if (album.getId() == -1)
			return false;
		// 首先根据ID列出所有图片数据
		List<?> photos = obj.list(album.getId().intValue());
		List<String> paths = new ArrayList<String>();
		for (Object albumphoto : photos) {
			Albumphoto tmp = (Albumphoto) albumphoto;
			paths.add(tmp.getFileserverpath());
			paths.add(tmp.getThumbpath());
		}
		// 采用事务删除数据，先删除图片数据，后删除相册信息
		String deletePhoto = "DELETE FROM albumphoto WHERE albumid=?";
		String deleteAlbum = "DELETE FROM album WHERE id=?";
		boolean flag = true;
		try {
			QueryHelper.setAutoCommit();
			QueryHelper.commitUpdate(deletePhoto,album.getId());
			QueryHelper.commitUpdate(deleteAlbum,album.getId());
			QueryHelper.commit();
		} catch (Exception e) {
			flag = false;
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				logger.error("删除相册时出现异常：{}", e1.getMessage());
				throw new ErrMsgException("删除相册时出现异常，请联系管理员！" + e1.getMessage());
			}
			logger.error("删除相册时出现异常：{}", e.getMessage());
			throw new ErrMsgException("删除相册时出现异常，请联系管理员！" + e.getMessage());
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				logger.error("删除相册时出现异常：{}", e2.getMessage());
				throw new ErrMsgException("删除相册时出现异常，请联系管理员！" + e2.getMessage());
			}
		}
		// 数据删除成功后删除硬盘上文件,无论文件是否存在，在删除时不返回任何异常
		if (flag){
			for (String path:paths){
				FileUtils.deleteQuietly(new File(RequestContext.root()+path));
			}
		}
		return true;
	}

}
